﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml.Helpers;

namespace Windows8Accelerator.Core.Xaml.Controls
{
    public static class ProgressBarManager 
    {
        private static int WorksPending = 0;

        public static void AddWork()
        {
            AppHelperBase.Instance.RunOnUIAsync(
                () =>
                {
                    WorksPending++;
                    UpdateVisibility();
                });
        }

        public static void RemoveWork()
        {
            AppHelperBase.Instance.RunOnUIAsync(
                () =>
                {
                    WorksPending--;
                    UpdateVisibility();
                });
        }

        private static void UpdateVisibility()
        {
            BindingSource.IsVisible = WorksPending > 0;
        }

        public static WorkPending NewWork()
        {
            return new WorkPending();
        }

        private static ProgressBarBindingSource _BindingSource = new ProgressBarBindingSource();
        public static ProgressBarBindingSource BindingSource
        {
            get { return _BindingSource; }
        }

        public class ProgressBarBindingSource : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;

            private void OnPropertyChanged(string property)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(property));
            }

            private bool _IsVisible = false;
            public bool IsVisible
            {
                get { return this._IsVisible; }
                set 
                { 
                    this._IsVisible = value;
                    OnPropertyChanged("IsVisible");
                }
            }

        }

        public class WorkPending : IDisposable
        {
            public WorkPending() 
            {
                ProgressBarManager.AddWork();
            }

            public void Dispose()
            {
                ProgressBarManager.RemoveWork();
            }
        }
    }


}
